﻿//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;

//namespace Business.Utils
//{
//    internal class Class3
//    {
//    }
//}

using OfficeOpenXml; // 使用 EPPlus 的命名空间
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.IO;


public class ExcelExporter
{
    public byte[] ExportToExcel<T>(List<T> data, string sheetName = "Sheet1")
    {
        using (ExcelPackage excelPackage = new ExcelPackage())
        {
            // 创建工作表
            ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(sheetName);

            // 获取类型属性
            var properties = typeof(T).GetProperties();

            // 写入表头
            for (int i = 0; i < properties.Length; i++)
            {
                worksheet.Cells[1, i + 1].Value = properties[i].Name;
                worksheet.Cells[1, i + 1].Style.Font.Bold = true;
                worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Cyan);
            }

            // 写入数据
            for (int row = 0; row < data.Count; row++)
            {
                for (int col = 0; col < properties.Length; col++)
                {
                    worksheet.Cells[row + 2, col + 1].Value = properties[col].GetValue(data[row]);
                }
            }

            // 自动调整列宽
            worksheet.Cells.AutoFitColumns();

            return excelPackage.GetAsByteArray();
        }
    }

    public void SaveToFile(byte[] excelData, string filePath)
    {
        File.WriteAllBytes(filePath, excelData);
    }
}
